# -*- coding: utf-8 -*-
#
# Author:: Jonny
# Date:: 2022/4/25
from config.private_config import (
    BAIDU_API_KEY,
    BAIDU_SECRET_KEY,
    BAIDU_API_KEY2,
    BAIDU_SECRET_KEY2,
    BAIDU_OCR_URL,
    BAIDU_TOKEN_URL,
    baidu_ocr_request_url,
)
from submodules.common.lib.log_ import get_logger

logger = get_logger()

import requests

import sys
import json
import base64

# 保证兼容python2以及python3
IS_PY3 = sys.version_info.major == 3
if IS_PY3:
    from urllib.request import urlopen
    from urllib.request import Request
    from urllib.error import URLError
    from urllib.parse import urlencode
    from urllib.parse import quote_plus
else:
    import urllib2
    from urllib import quote_plus
    from urllib2 import urlopen
    from urllib2 import Request
    from urllib2 import URLError
    from urllib import urlencode

# 防止https证书校验不正确
import ssl

ssl._create_default_https_context = ssl._create_unverified_context


def fetch_token():
    params = {
        "grant_type": "client_credentials",
        "client_id": BAIDU_API_KEY2,
        "client_secret": BAIDU_SECRET_KEY2,
    }
    post_data = urlencode(params)
    if IS_PY3:
        post_data = post_data.encode("utf-8")
    req = Request(BAIDU_TOKEN_URL, post_data)
    try:
        f = urlopen(req, timeout=5)
        result_str = f.read()
    except URLError as err:
        print(err)
    if IS_PY3:
        result_str = result_str.decode()

    result = json.loads(result_str)

    if "access_token" in result.keys() and "scope" in result.keys():
        if not "brain_all_scope" in result["scope"].split(" "):
            print("please ensure has check the  ability")
            exit()
        return result["access_token"]
    else:
        print("please overwrite the correct API_KEY and SECRET_KEY")
        exit()


"""
数字识别
"""


def get_verify_code_by_baidu_ocr(file_path):
    # 二进制方式打开图片文件
    # f = open('D:\screenshot-20220425-023441.png', 'rb')
    f = open(file_path, "rb")
    img = base64.b64encode(f.read())

    params = {"image": img, "detect_direction": "true"}
    access_token = fetch_token()
    baidu_ocr_request_url = baidu_ocr_request_url + "?access_token=" + access_token
    headers = {"content-type": "application/x-www-form-urlencoded"}
    response = requests.post(baidu_ocr_request_url, data=params, headers=headers)
    # if response:
    #     print(response.json())

    logger.info(f"response:{response.json()}")

    word = ""
    for item in response.json()["words_result"]:
        word += item["words"]
    return word


if __name__ == "__main__":
    file_path = "D:\\code\\wendao\\test\\9951.png"
    res = get_verify_code_by_baidu_ocr(file_path)
    print(res)
